import { _decorator, Component, Label, Node, Sprite } from 'cc';
const { ccclass, property } = _decorator;
/**
 * 冷却时间
 */
@ccclass('ColdTimer')
export class ColdTimer extends Component {

    private _lable: Label;
    private _sprite: Sprite;

    private _total: number = 0;
    private _time: number = 0;
    private _running: boolean = false;
    private _onColdDown: () => void;
    private _target: any;

    protected onLoad(): void {
        this._lable = this.node.getChildByName("Label").getComponent(Label);
        this._sprite = this.node.getComponent(Sprite);
    }

    protected onEnable(): void {
        this._running = false;
    }

    start() {

    }

    update(deltaTime: number) {
        if(!this._running) {
            return;
        }

        this._time += deltaTime;
        if(this._time >= this._total) {
            this._running = false;
            this._time = 0;
            this._lable.string = "0.0";
            this._onColdDown?.call(this._target);
        }else {
            let leftTime = this._total - this._time;
            let percent= leftTime / this._total;
            this._sprite.fillRange = percent;
            this._lable.string = leftTime.toFixed(1);
        }
    }

    onColdDown(onColdDown:()=> void,target?:any) {
        this._onColdDown = onColdDown;
        this._target = target;
    }

    startColdTime(total: number) {
        this._total = total;
        this._time = 0;
        this._running = true;
    }
}


